<template>
  <!-- 项目管理授权书 -->

  <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="editModel == 0 ? {} : rules">
    <a-spin :spinning="loading">
      <!-- 表单 -->
      <a-card>
        <title-name title="项目管理授权书"></title-name>
        <custom-form :formList="formList" :form="form" :is-emit="false" :editModel="editModel == 0 ? '' : ''"> </custom-form>
        <div class="mb12">具体授权内容</div>

        <a-button :disabled="editModel == 0" type="primary" class="mb12" icon="plus" @click="addTabel"> 新增 </a-button>
        <s-table bordered ref="table" size="default" rowKey="key" :columns="columns" :data="loadData" :alert="true" show-size-changer show-quick-jumper :showPagination="false">
          <template slot="action" slot-scope="text, record, index">
            <a-popconfirm title="确定要删除?" @confirm="() => delItem(index)">
              <a v-if="editModel != 0 && record.isDeleted != 1">删除</a>
            </a-popconfirm>
          </template>
          <template v-for="col in ['authorizeContent', 'department', 'phone', 'workRequirements']" :slot="col" slot-scope="text, record">
            <div :key="col" :class="record.authorizeContent || record.department || record.phone || record.workRequirements ? 'form-item' : ''">
              <BaseInput v-model="record[col]" :disabled="editModel == 0" :maxLength="300" />
            </div>
          </template>
        </s-table>
      </a-card>
    </a-spin>
    <DialogForm
      ref="dialogForm"
      :visible.sync="visible"
      :edit-model="'2'"
      :form="initData"
      header-title="增加授权内容"
      :width="800"
      :height="1100"
      :isEmit="false"
      :rules="rulesDialog"
      :form-list="formListDialog"
      @confirm="submitForm"
      :clearForm="false"
      :styles="{ width: '550px' }"
    />
  </a-form-model>
</template>

<script>
import { api } from '@/api/projectManagementPlanning/projectAuthorizationLetter'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BSelect from '@/components/BComponents/BSelect'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople'
import DialogForm from '@/components/DialogForm' // 弹窗
import { createValidator, idCard } from '@/utils/regExpression'
export default {
  name: 'projectAuthorizationLetter',
  extends: new BaseEditPage(),
  components: {
    SelectProject,
    BSelect,
    SelectSubCompany,
    ASelectOrgPeople,
    DialogForm
  },
  props: {
    baseFormInfo: {
      // 是否作为审批详情
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      loading: false, // 加载控件
      visible: false, //人员选择控件
      editModel: 1, // 操作状态:0 查看;1 编辑
      form: { detailList: [], projectOrgId: '', }, // 表单
      id: '',
      initData: {},
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      loadData: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.form.detailList || []
          })
        })
      },
      update: api.updateList,
      rules: {
        authorizerId: [{ required: true, message: '请选择' }],
        clientNum: [{ required: true, validator: createValidator(idCard, '号码格式不正确', true), trigger: 'blur' }],

        clientDate: [{ required: true, message: '请输入' }],
        client: [{ required: true, message: '请输入' }]
      }, // 校验规则
      rulesDialog: {
        authorizeType: [{ required: true, message: '请选择' }]
      },
      init: false, // 初始化控件
      selectDepartment: []
    }
  },
  watch: {},
  computed: {
    formList() {
      console.log(this.form)
      return [
        {
          keyName: 'authorizerId',
          type: ASelectOrgPeople,
          label: '委托人',
          disabled: this.editModel == 0,
          placeholder: '请选择姓名',
          attrs: {
            form: this.form,
            keyValue: 'projectOrgId',
            // needRootOrgId: true,
            init: false
          },

          onSelectChange: (e) => {
            this.$set(this.form, 'clientNum', e.idCard)
          }
        },
        {
          keyName: 'clientNum',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '委托人身份证号'
        },
        {
          keyName: 'clientDate',
          type: 'a-range-picker',
          disabled: this.editModel == 0,
          label: '授权时限',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },

         {
          keyName: 'client',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '授权人'
        },
      ]
    },

    formListDialog() {
      return [
        // 手写普通选择框
        {
          type: 'a-select',
          keyName: 'authorizeType',
          label: '授权分类',
          span: 24,
          replaceFields: {
            value: 'authorizeType', // 默认为value
            label: 'authorizeType' // 默认为label
          },
          data: this.selectDepartment
        }
      ]
    },
    columns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          customRender(text, record, index) {
            return index + 1
          }
        },
        {
          title: '授权分类',
          dataIndex: 'authorizeType',

          width: '10%',
          customRender: (text, row, index) => {
            let obj = {
              children: text,
              attrs: {}
            }
            let lastIndex = -1
            let firstIndex = this.form.detailList.findIndex((v) => v.authorizeType == text)
            this.form.detailList.map((m, i) => {
              if (m.authorizeType == text) {
                lastIndex = i
              }
            })
            if (index === 0) {
              obj.attrs.rowSpan = lastIndex === firstIndex ? 1 : lastIndex + 1 - firstIndex
            } else {
              // 若该行考核内容和上一行一致，则使其隐藏
              if (this.form.detailList[index - 1].authorizeType === text) {
                obj.attrs.rowSpan = 0
                // 若不是，则往下合并与改行内容一致行的总行数
              } else {
                obj.attrs.rowSpan = lastIndex === firstIndex ? 1 : lastIndex + 1 - firstIndex
              }
            }

            return obj
          }
        },
        {
          title: '授权内容',
          dataIndex: 'authorizeContent',
          width: '30%',
          scopedSlots: { customRender: 'authorizeContent' }
        },
        {
          title: '工作要求',
          dataIndex: 'workRequirements',
          width: '30%',
          scopedSlots: { customRender: 'workRequirements' }
        },
        {
          title: '部门会签及联系人',
          dataIndex: 'department',
          width: '15%',
          scopedSlots: { customRender: 'department' }
        },
        {
          title: '联系方式',
          width: '10%',
          dataIndex: 'phone',
          scopedSlots: { customRender: 'phone' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '5%',
          scopedSlots: { customRender: 'action' }
        }
      ]
    }
  },
  created() {},
  mounted() {
    // 不为添加时请求详情
    // this.form.authorizer = this.$userInfo().username
    // this.getDetailData()
  },

  watch: {
    baseFormInfo: {
      handler(val) {
        this.getDetailData()
        console.log(11111111111)
        // this.form.projectOrgId = this.baseFormInfo.projectOrgId
        // console.log(this.form)
      }
    }
  },

  methods: {
    addTabel() {
      this.initData.authorizeType = undefined
      this.visible = true
      this.$nextTick(() => {
        const requireDom = document.querySelectorAll('.ant-form-item-required')
        const requireDomArray = Array.from(requireDom)
        requireDomArray.forEach((item) => {
          item.parentNode.nextSibling.children[0].children[0].classList.add('requiredFormItem') // 找到'.ant-form-item-children'元素添加样式
        })
      })
    },
    submitForm(data) {
      let index = 0

      this.form.detailList.forEach((e, i) => {
        // 研发类没有typeTwo, 无法用type作比较
        if (data.authorizeType == e.authorizeType) {
          index = i
        }
      })
      console.log(index)

      this.form.detailList.splice(index + 1, 0, {
        authorizeType: data.authorizeType,
        authorizeContent: '',
        mainId: this.id,
        workRequirements: '',
        department: '',
        phone: ''
      })
      this.initSelectDepartment()
      console.log(this.form.detailList)
      this.visible = false
      this.$refs.table.refresh()
    },
    initSelectDepartment() {
      this.selectDepartment = []
      this.form.detailList?.forEach((e, i) => {
        if (i == 0) {
          this.selectDepartment.push(e)
        }
        if (i > 0 && e.authorizeType != this.form.detailList[i - 1].authorizeType) {
          this.selectDepartment.push(e)
        }
      })
    },
    getDetailData() {
      this.loading = true
      api
        .getDetails({ id: this.id, version: this.$route.query.version || void 0 })
        .then((res) => {
          this.loading = false
          console.log(res.data)
          this.form = { ...res.data }
          // this.form.clientId = this.form.clientId || this.$userInfo().id
          this.form.projectOrgId = this.baseFormInfo.projectOrgId

          if (this.form.clientStartDate && this.form.clientEndDate) {
            this.form.clientDate = []
            this.form.clientDate.push(this.form.clientStartDate)
            this.form.clientDate.push(this.form.clientEndDate)
          }
          this.initSelectDepartment()
          this.$refs.table.refresh()
          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    },
    validateForm() {
      let flag1 = true
      let flag2 = true
      let flag3 = true
      this.$refs.ruleForm.validate((e) => {
        flag1 = e
      })
      //检测若有填写一行,填写是否完整
      this.form.detailList?.forEach((i) => {
        if (i.phone) {
          if (!i.department || !i.workRequirements || !i.authorizeContent) {
            flag2 = false
          }
        }
        if (i.department) {
          if (!i.phone || !i.workRequirements || !i.authorizeContent) {
            flag2 = false
          }
        }
        if (i.workRequirements) {
          if (!i.department || !i.phone || !i.authorizeContent) {
            flag2 = false
          }
        }
        if (i.authorizeContent) {
          if (!i.department || !i.workRequirements || !i.phone) {
            flag2 = false
          }
        }
      })
      for (let k = 0; k < this.form.detailList.length; k++) {
        let i = this.form.detailList[k]

        if (i.phone || i.department || i.workRequirements || i.authorizeContent) {
          flag3 = true
          break
        } else {
          flag3 = false
        }
      }

      if (!flag3) {
        this.$warning({
          title: '提示',
          content: '请至少填写一行数据!',
          okText: '确定'
        })
        // this.$message.warning('请至少填写一行数据!')
      } else if (!flag2) {
        this.$warning({
          title: '提示',
          content: '请将数据填写完整!',
          okText: '确定'
        })
        // this.$message.warning('请填写完整!')
      }

      if (flag1 && flag2 && flag3) {
        return true
      } else {
          this.$message.warning("请填写完所有必填项信息")
        return false
      }
    },
    delItem(index) {
      this.form.detailList.splice(index, 1)
      this.$refs.table.refresh()
    },
    projectAuthorizationLetterSaveDrafts() {
      this.handleSubmit(0)
    },
    projectAuthorizationLetterSubmit() {
      if (this.validateForm()) {
        this.handleSubmit(1)
      }
    },

    /**
     * 提交表单
     */
    handleSubmit(status) {
      let form = this.$clone(this.form)
      form.id = this.form.id
      delete form.createTime
      console.log(form)
      if (form.detailList?.length == 0) {
        form.detailList.push({ mainId: this.id })
      }
      form.status = status
      console.log(form.clientDate)
      if (form.clientDate?.length > 0) {
        form.clientStartDate = form.clientDate[0]
        form.clientEndDate = form.clientDate[1]
      }
      delete form.clientDate
      if (status == 1) {
        this.handleSecondSub(form)
        return
      }
      this.loading = true
      api
        .updateList(form)
        .then(() => {
          this.loading = false
          this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
          this.$multiTab.close()
        })
        .catch(() => {
          this.loading = false
          this.$message.warning(err.data.message)
        })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .form-item  {
  .ant-input:not([disabled]),
  .ant-select:not(.ant-select-disabled) .ant-select-selection,
  .ant-calendar-picker-input,
  .ant-input-number:not([disabled]),
  .ant-cascader-picker {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
  .ant-input-disabled,
  .ant-input-number-disabled .ant-input-number-input,
  .ant-time-picker-input[disabled] {
    border-color: #d9d9d9 !important;
    background-color: #f5f5f5 !important;
  }
  .remark {
    .ant-input {
      border-color: inherit;
      background-color: initial;
    }
  }
}
</style>
